<?php
require_once 'NonceRequest.php';
require_once 'NonceResponse.php';
require_once 'Database.php';
/*
 * return a nonce for the client to use in subsequent encryption operations
 * nonce returned is only good for a short period of time, so this call and
 * a subsequent authorize or authenticate call should be made within a few
 * seconds.
 */
function getNonce(NonceRequest $nonceRequest)
{
    try
    {

        $db = new Database();
        $db->connect();
        $db->logEvent('GetNonce.php::getNonce', 51, 'enter try block, db connected');
        $encodedAndEncryptedClientNonce = $nonceRequest->EncryptedClientNonce;
        $db->logEvent('GetNonce.php::getNonce', 29, 'client Nonce ( AS SENT ):' . $encodedAndEncryptedClientNonce);
        $encryptedClientNonce = base64_decode($encodedAndEncryptedClientNonce);
        $db->logEvent(__METHOD__, 29, 'client Nonce (base64_decoded): ' . $encryptedClientNonce . " || String length: " . strlen($encryptedClientNonce));
        // decrypt the user nonce using shared key.
        $clientNonce = $db->aesDecrypt( $encryptedClientNonce, $nonceRequest->UserName);
        $username = $nonceRequest->UserName;
        $db->logEvent('GetNonce.php::getNonce', 29, 'client Nonce from ' . $username . ' (DECRYPTED):' . $clientNonce);
  		//reduce client nonce to 36 characters
        $clientNonce = substr($clientNonce,0,36);
        //get the value of the current server nonce.
        $serverNonce = $db->getNonce($nonceRequest->UserName);
        //server appends server nonce to user nonce to form combined nonce
        $combinedNonce = $clientNonce . $serverNonce;
        $encryptedCombinedNonce = $db->aesEncrypt( $combinedNonce, $nonceRequest->UserName);
        $nonceToReturn = new NonceResponse(base64_encode($encryptedCombinedNonce)) ;
        $db->logEvent('GetNonce.php::getNonce', 51, 'finish try block');
    }
    catch (Exception $ee)
    {
        $db->logEvent(__METHOD__, 1, $ee->getMessage());
        //give caller a useless nonce
        $nonceToReturn = new NonceResponse(base64_encode('exception'));
    }
    $db->logEvent('GetNonce.php::getNonce', 52, 'returning ' . $nonceToReturn->Nonce);
    return $nonceToReturn;
}
?>